package com.rongji.dfish.demo.intro.controller;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rongji.dfish.base.Utils;
import com.rongji.dfish.base.crypt.CryptFactory;
import com.rongji.dfish.base.crypt.StringCryptor;
import com.rongji.dfish.base.info.DataBaseInfo;
import com.rongji.dfish.base.info.EthNetInfo;
import com.rongji.dfish.base.info.ServletInfo;
import com.rongji.dfish.base.info.SystemInfo;
import com.rongji.dfish.base.util.FileUtil;
import com.rongji.dfish.framework.SystemData;
import com.rongji.dfish.framework.controller.BaseController;
import com.rongji.dfish.ui.command.DialogCommand;
import com.rongji.dfish.ui.helper.FormPanel;
import com.rongji.dfish.ui.helper.Label;
import com.rongji.dfish.ui.layout.HorizontalLayout;
import com.rongji.dfish.ui.layout.View;
import com.rongji.dfish.ui.widget.Toggle;

@Controller
@RequestMapping("/pubInfo")
public class PubInfoController<HtmlPanel> extends BaseController{
	@SuppressWarnings("deprecation")
	@RequestMapping("/sysinfo")
	@ResponseBody
	public Object sysinfo(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		    View view = new View();
		    HorizontalLayout main=new HorizontalLayout("100%");
		    main.setScroll(true);
		    view.add(main);
		    FormPanel f1=new FormPanel("f_form1");
		    main.add(f1);
		    
		    f1.add(new Toggle().setText("系统信息").setOpen(true).setHr(true));
		    f1.add(new Label(null,"操作系统"));
		    SystemInfo sysinfo=SystemData.getInstance().getSysinfo();
		    f1.add(new Label("操作系统",sysinfo.getOperationSystem()));//操作系统
			f1.add(new Label("默认字符集",sysinfo.getFileEncoding()));//默认字符集
		    
			Set<String> macAdrs = null;
			try {
				macAdrs = EthNetInfo.getAllMacAddress();
			} catch (Exception ex) {
				macAdrs = new HashSet<String>();
			}
			StringBuilder macAdrStrB = new StringBuilder();
			for (Iterator iter = (Iterator) macAdrs.iterator(); iter.hasNext();) {
				Object item = iter.next();
				macAdrStrB.append("<nobr>");
				macAdrStrB.append(item);
				macAdrStrB.append("</nobr>");
				if (iter.hasNext()) {
					macAdrStrB.append(", ");
				}
			}
			
			
			f1.add(new Label("更多属性","[<a class='a-blue' href=\"#\" onclick=\"VM(this).cmd('showDetail')\">点击查看</a>]"));//内存大小
//			f1.add(new Label(null,"服务器信息"));
			f1.add(new Toggle().setText("服务器信息").setOpen(true).setHr(true));
			ServletInfo servinfo=SystemData.getInstance().getServletInfo();
			f1.add(new Label("servlet版本",servinfo.getServletVersion()));//servlet版本
			f1.add(new Label("应用路径",servinfo.getServletRealPath()));//应用路径
		
			String memStatus=FileUtil.getHumanSize(Runtime.getRuntime().freeMemory()) +
			"(free) / " + FileUtil.getHumanSize(Runtime.getRuntime().totalMemory());
			Label memLab=new Label("内存大小(JVM)",memStatus);
			f1.add(memLab);//内存大小
			
//			double procLoad=SystemInfoCollector.getInstance().getProcessCpuUsageSun();
			
//			String cupText=(procLoad<0?"[不可用]":(((int)(procLoad*1000))/10.0+"%"));
//			f1.add(new Label("CPU(本进程)", cupText));//CPU(进程/整机)
			
//			int tCount=ManagementFactory.getThreadMXBean().getThreadCount();
//			Text tCountLab=new Text("","","当前线程数",tCount);
//			f1.add(tCountLab);//当前会话数
//			f1.add(new Label(null,"数据库信息"));
			f1.add(new Toggle().setText("数据库信息").setOpen(true).setHr(true));
			DataBaseInfo dbinfo=SystemData.getInstance().getDataBaseInfo();
			if(dbinfo==null){
				//数据库无法连接，或者不支持该数据库！
				f1.add(new Label("错误信息","数据库无法连接，或者不支持该数据库！"));
			}else{
				f1.add(new Label("名称",dbinfo.getDatabaseProductName()));//名称
				f1.add(new Label("版本",dbinfo.getDatabaseProductVersion()));//版本
				f1.add(new Label("连接字",dbinfo.getDatabaseUrl()));//连接字
				f1.add(new Label("用户",dbinfo.getDatabaseUsername()));//用户
			
	           
	        }
//			f1.add(new Ueditor("test","测试编辑器","欢迎使用编辑器").setHeight(120));
			DialogCommand dialog=new DialogCommand("win","std","详细信息",DialogCommand.WIDTH_MEDIUM,DialogCommand.HEIGHT_LARGE,DialogCommand.POSITION_MIDDLE,
					"pubInfo/showDetail");
			view.addCommand("showDetail",dialog);
			return view;
         }
	@RequestMapping("/showDetail")
	@ResponseBody
	public Object showDetail(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		    View view = new View();
		    FormPanel form=new FormPanel("f_form2");
		    view.add(form);
		    form.setScroll(true);
		    
		    form.add(new Toggle().setText("环境信息").setOpen(true).setHr(true));
			showMap(form,System.getenv());
			form.add(new Toggle().setText("属性信息").setOpen(true).setHr(true));
			showMap(form,System.getProperties());
		    return view;
	}
	private void showMap(FormPanel panel,Map map){
		Set<?> keyList=new TreeSet(map.keySet());
		
		for(Object o:keyList){
			System.out.println(o.getClass().getName());
			String title=String.valueOf(o);
			String value=String .valueOf(map.get(o));

			String text="<div style=word-break:break-all>"+Utils.escapeXMLword(value)+"</div>";
			
			if(title.length()>20){
				Label titleLab=new Label("",title+" :");
//				titleLab.setFullLine(true);
				panel.add(titleLab);
				Label textLab=new Label("",text);
//				textLab.setFilter(false);
				panel.add(textLab);
			}else{
				Label textLab=new Label(title,text);
//				textLab.setFilter(false);
				panel.add(textLab);
			}
		}
	}
	
	private String escape(String value) {
		// TODO Auto-generated method stub
		return null;
	}

	private static byte[] pubKeyBtyeArray=new byte[]{0, -39, 95, 60, -26, -55, 1, 113, 119};
	private static byte[] modBtyeArray=new byte[]{0, -102, -10, -3, 54, 25, -122, 16, 85, 110, 6, -8, 46, -73, 38, 29, 37, 3, -62, 57, 40, 98, 95, 97, 19, -100, -41, 40, 108, 31, -106, -18, 67, -68, 67, 70, 19, -64, -52, 56, 78, 73, 73, 88, 17, -58, -56, 38, 77, -86, -123, -110, 97, -114, -46, 69, 61, 104, 40, 10, -49, 45, 28, 124, 121, 21, -61, -79, -104, -118, -64, -3, 43, -29, -80, 46, 53, 72, 120, 84, 3, 20, 36, -125, -97, 83, 49, 2, -43, -117, 12, -104, -59, -66, 94, 3, -103, -47, 74, -40, -86, -72, 58, 121, -71, -56, 49, -98, 32, -103, -53, 70, -65, 125, -20, -60, 120, -7, -80, -17, 6, 23, 23, -105, 88, -100, -58, 36, -20, 79};
	private static StringCryptor sc_beta =
	      CryptFactory.getStringCryptor(
	          CryptFactory.RSA, CryptFactory.UTF8,
	          CryptFactory.BASE64, new BigInteger[] {
	          new BigInteger(pubKeyBtyeArray),
	          new BigInteger("0"),
	          new BigInteger(modBtyeArray)});
	public static final Map<String,String> getLicenseData(){
		Map<String,String> result=new TreeMap<String,String>();
		try{
		ResourceBundle rb=ResourceBundle.getBundle("com.rongji.dfish.engines.xmltmpl.license");
		String code=rb.getString("code");
		String decode=sc_beta.decrypt(code);
		for(String pair:decode.split("&")){
			String[]s=pair.split("=");
			if(s.length<2)continue;
			try {
				result.put(s[0], java.net.URLDecoder.decode(s[1],"UTF-8"));
			} catch (UnsupportedEncodingException e) {}
		}
		}catch(Throwable t){}
		return result;
	}
}
	
